package service

import (
	"github.com/jinzhu/gorm"
	"naio/config"
	"naio/db/mysql"
	"naio/errs"
	"naio/model"
	"time"
)

type ICategoryService interface {
	GetCategoryList(pid, page, size int) (*[]model.CategoryModel, int)
	GetCategoryById(id int) *model.CategoryModel
	GetCategoryByName(name string) *model.CategoryModel
	AddCategory(category *model.CategoryModel)
	UpdateCategory(category *model.CategoryModel)
}

type CategoryService struct {
	Conf *config.BaseConfig
}

func NewCategoryService(conf *config.BaseConfig) ICategoryService {
	return &CategoryService{Conf: conf}
}

//TODO done
func (s *CategoryService) GetCategoryList(pid, page, size int) (*[]model.CategoryModel, int) {
	var list []model.CategoryModel
	var total int
	db := mysql.GetMysqlPool().GetMysqlDB()
	err := db.Where("del=0 AND parent_id=?", pid).Offset((page - 1) * size).Limit(size).Order("sort").Find(&list).Error
	if err != nil {
		panic(err)
	}
	db.Table("category").Where("del=0 AND parent_id=?", pid).Count(&total)
	return &list, total
}

//TODO: done
func (s *CategoryService) GetCategoryById(id int) *model.CategoryModel {
	one := &model.CategoryModel{}
	db := mysql.GetMysqlPool().GetMysqlDB()
	err := db.Table("category").Where("del=0 AND id=?", id).First(&one).Error
	//if err == gorm.ErrRecordNotFound {
	//	// do something
	//	panic(errs.NewMyAPIError(errs.ErrorCategory, "category不存在"))
	//}
	if err != nil {
		panic(err)
	}
	return one
}

//TODO: done
func (s *CategoryService) GetCategoryByName(name string) *model.CategoryModel {
	one := &model.CategoryModel{}
	db := mysql.GetMysqlPool().GetMysqlDB()
	err := db.Table("category").Where("del=0 AND name=?", name).First(&one).Error
	if err == gorm.ErrRecordNotFound {
		// do something
		panic(errs.NewMyAPIError(errs.ErrorCategoryNotExist, "category不存在"))
	}
	if err != nil {
		panic(err)
	}
	return one
}

//TODO: done
func (s *CategoryService) AddCategory(category *model.CategoryModel) {
	db := mysql.GetMysqlPool().GetMysqlDB()
	if err := db.Create(category).Error; err != nil {
		panic(err)
	}
}

//TODO: done
func (s *CategoryService) UpdateCategory(category *model.CategoryModel) {
	db := mysql.GetMysqlPool().GetMysqlDB()
	if err := db.Save(&category).Error; err != nil {
		panic(err)
	}
	syncSubCategoryAndGoodsOnline(category.ParentId, category.Id, category.Online)
}

//TODO: done
//同步其子分类和商品的上下架状态
func syncSubCategoryAndGoodsOnline(pid, categoryId, online int) {
	db := mysql.GetMysqlPool().GetMysqlDB()
	if pid != 0 {
		err := db.Table("goods").Where("del=0 AND category_id=?", categoryId).Updates(map[string]interface{}{"update_time": time.Now(), "online": online}).Error
		if err != nil {
			panic(err)
		}
	} else {
		//UpdateSubCategoryOnline
		err := db.Table("category").Where("del=0 AND category_id=?", categoryId).Update("online=?", online).Update("update_time=?", time.Now()).Error
		if err != nil {
			panic(err)
		}
		ids, err := querySubCategoryIdByParentId(pid)
		if err != nil {
			panic(err)
		}
		for _, v := range *ids {
			err := db.Table("goods").Update("update_time=?", time.Now()).Update("online=?", online).Where("del=0 AND category_id=?", v)
			if err != nil {
				panic(err)
			}
		}
	}
}

//TODO: done
// 查询子分类id号
func querySubCategoryIdByParentId(pid int) (*[]int, error) {
	db := mysql.GetMysqlPool().GetMysqlDB()
	rows, err := db.Table("category").Where("del=0").Where("parent_id=?", pid).Select("id").Rows()
	if err != nil {
		panic(err)
	}
	defer rows.Close()

	var ids []int
	for rows.Next() {
		id := 0
		err := rows.Scan(&id)
		if err != nil {
			return nil, err
		}
		ids = append(ids, id)
	}
	return &ids, nil
}
